<?php 
/**
 * 管理中心仓库管理相关函数
 * $Author: 王海龙 $
 * $Id: lib_warehouse.php 17217 2014-10-10 12:05:22 王海龙 $
 */

if (!defined('IN_ECS'))
{
    die('Hacking attempt');
}

/**
 *  获取订单列表信息
 *
 * @access  public
 * @param
 *
 * @return void
 */
function order_list()
{  
    $result = get_filter();
   
    if ($result === false)
    {
        /* 过滤信息 */
        $filter['order_sn'] = empty($_REQUEST['order_sn']) ? '' : trim($_REQUEST['order_sn']);
        if (!empty($_GET['is_ajax']) && $_GET['is_ajax'] == 1)
        {
            $_REQUEST['consignee'] = json_str_iconv($_REQUEST['consignee']);
            //$_REQUEST['address'] = json_str_iconv($_REQUEST['address']);
        }
        $filter['consignee'] = empty($_REQUEST['consignee']) ? '' : trim($_REQUEST['consignee']);
        $filter['email'] = empty($_REQUEST['email']) ? '' : trim($_REQUEST['email']);
        $filter['address'] = empty($_REQUEST['address']) ? '' : trim($_REQUEST['address']);
        $filter['zipcode'] = empty($_REQUEST['zipcode']) ? '' : trim($_REQUEST['zipcode']);
        $filter['tel'] = empty($_REQUEST['tel']) ? '' : trim($_REQUEST['tel']);
        $filter['mobile'] = empty($_REQUEST['mobile']) ? 0 : intval($_REQUEST['mobile']);
        $filter['country'] = empty($_REQUEST['country']) ? 0 : intval($_REQUEST['country']);
        $filter['province'] = empty($_REQUEST['province']) ? 0 : intval($_REQUEST['province']);
        $filter['city'] = empty($_REQUEST['city']) ? 0 : intval($_REQUEST['city']);
        $filter['district'] = empty($_REQUEST['district']) ? 0 : intval($_REQUEST['district']);
        $filter['shipping_id'] = empty($_REQUEST['shipping_id']) ? 0 : intval($_REQUEST['shipping_id']);
        $filter['pay_id'] = empty($_REQUEST['pay_id']) ? 0 : intval($_REQUEST['pay_id']);
        $filter['order_status'] = isset($_REQUEST['order_status']) ? intval($_REQUEST['order_status']) : -1;
        $filter['shipping_status'] = isset($_REQUEST['shipping_status']) ? intval($_REQUEST['shipping_status']) : -1;
        $filter['pay_status'] = isset($_REQUEST['pay_status']) ? intval($_REQUEST['pay_status']) : -1;
        $filter['user_id'] = empty($_REQUEST['user_id']) ? 0 : intval($_REQUEST['user_id']);
        $filter['user_name'] = empty($_REQUEST['user_name']) ? '' : trim($_REQUEST['user_name']);
        $filter['composite_status'] = isset($_REQUEST['composite_status']) ? intval($_REQUEST['composite_status']) : -1;
        $filter['daodankuaidi'] = isset($_REQUEST['daodankuaidi']) ? intval($_REQUEST['daodankuaidi']) : 0;
        $filter['group_buy_id'] = isset($_REQUEST['group_buy_id']) ? intval($_REQUEST['group_buy_id']) : 0;
        $filter['invoice_no'] = isset($_REQUEST['invoice_no']) ? intval($_REQUEST['invoice_no']) : 0;
        $filter['sort_by'] = empty($_REQUEST['sort_by']) ? 'add_time' : trim($_REQUEST['sort_by']);
        $filter['sort_order'] = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        $filter['start_time'] = empty($_REQUEST['start_time']) ? '' : (strpos($_REQUEST['start_time'], '-') > 0 ?  local_strtotime($_REQUEST['start_time']) : $_REQUEST['start_time']);
        $filter['end_time'] = empty($_REQUEST['end_time']) ? '' : (strpos($_REQUEST['end_time'], '-') > 0 ?  local_strtotime($_REQUEST['end_time']) : $_REQUEST['end_time']);

        $where = 'WHERE 1 ';
        if ($filter['order_sn'])
        {
            $where .= " AND o.order_sn LIKE '%" . mysql_like_quote($filter['order_sn']) . "%'";
        }
        if ($filter['invoice_no'])
        {
            $where .= " AND o.invoice_no LIKE '%" . mysql_like_quote($filter['invoice_no']) . "%'";
        }
        if ($filter['consignee'])
        {
            $where .= " AND o.consignee LIKE '%" . mysql_like_quote($filter['consignee']) . "%'";
        }
        if ($filter['email'])
        {
            $where .= " AND o.email LIKE '%" . mysql_like_quote($filter['email']) . "%'";
        }
        if ($filter['address'])
        {
            $where .= " AND o.address LIKE '%" . mysql_like_quote($filter['address']) . "%'";
        }
        if ($filter['zipcode'])
        {
            $where .= " AND o.zipcode LIKE '%" . mysql_like_quote($filter['zipcode']) . "%'";
        }
        if ($filter['tel'])
        {
            $where .= " AND o.tel LIKE '%" . mysql_like_quote($filter['tel']) . "%'";
        }
        if ($filter['mobile'])
        {
            $where .= " AND o.mobile LIKE '%" .mysql_like_quote($filter['mobile']) . "%'";
        }
        if ($filter['country'])
        {
            $where .= " AND o.country = '$filter[country]'";
        }
        if ($filter['province'])
        {
            $where .= " AND o.province = '$filter[province]'";
        }
        if ($filter['city'])
        {
            $where .= " AND o.city = '$filter[city]'";
        }
        if ($filter['district'])
        {
            $where .= " AND o.district = '$filter[district]'";
        }
        if ($filter['shipping_id'])
        {
            $where .= " AND o.shipping_id  = '$filter[shipping_id]'";
        }
        if ($filter['pay_id'])
        {
            $where .= " AND o.pay_id  = '$filter[pay_id]'";
        }
        if ($filter['order_status'] != -1)
        {
            $where .= " AND o.order_status  = '$filter[order_status]'";
        }
        if ($filter['shipping_status'] != -1)
        {
            $where .= " AND o.shipping_status = '$filter[shipping_status]'";
        }
        if ($filter['pay_status'] != -1)
        {
            $where .= " AND o.pay_status = '$filter[pay_status]'";
        }
        if ($filter['user_id'])
        {
            $where .= " AND o.user_id = '$filter[user_id]'";
        }
        if ($filter['user_name'])
        {
            $where .= " AND u.user_name LIKE '%" . mysql_like_quote($filter['user_name']) . "%'";
        }
        if ($filter['start_time'])
        {
            $where .= " AND o.add_time >= '$filter[start_time]'";
        }
        if ($filter['end_time'])
        {
            $where .= " AND o.add_time <= '$filter[end_time]'";
        }

        //综合状态
        switch($filter['composite_status'])
        {
            case CS_AWAIT_PAY :
                $where .= order_query_sql('await_pay');
                break;

            case CS_AWAIT_SHIP :
                $where .= order_query_sql('await_ship');
                break;

            case CS_FINISHED :
                $where .= order_query_sql('finished');
                break;

            case PS_PAYING :
                if ($filter['composite_status'] != -1)
                {
                    $where .= " AND o.pay_status = '$filter[composite_status]' ";
                }
                break;
            case OS_SHIPPED_PART :
                if ($filter['composite_status'] != -1)
                {
                    $where .= " AND o.shipping_status  = '$filter[composite_status]'-2 ";
                }
                break;
            default:
                if ($filter['composite_status'] != -1)
                {
                    $where .= " AND o.order_status = '$filter[composite_status]' ";
                }
        }
        /* 如果管理员属于某个办事处，只列出这个办事处管辖的订单 */
        $sql = "SELECT agency_id FROM " . $GLOBALS['ecs']->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
        $agency_id = $GLOBALS['db']->getOne($sql);
        if ($agency_id > 0)
        {
            $where .= " AND o.agency_id = '$agency_id' ";
        }
        if($filter['daodankuaidi'] >0){
            $where .= " AND o.daodansong_id >0 AND   order_status NOT IN ('2','3','4') AND !(o.pay_status=0 AND o.pay_id = 1)";
        }
        /* 分页大小 */
        $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);

        if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
        {
            $filter['page_size'] = intval($_REQUEST['page_size']);
        }
        elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
        {
            $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
        }
        else
        {
            $filter['page_size'] = 15;
        }

        /* 记录总数 */
        if ($filter['user_name'])
        {
            $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('order_info') . " AS o ,".
                   $GLOBALS['ecs']->table('users') . " AS u " . $where;
        }
        else
        {
            $sql = "SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('order_info') . " AS o ". $where;
        }

        $filter['record_count']   = $GLOBALS['db']->getOne($sql);
        $filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;

        /* 查询 */
        $sql = "SELECT o.order_id,o.order_sn, o.add_time,o.pay_name, o.order_status, o.shipping_status, o.order_amount, o.money_paid, o.province, o.city, o.district, o.shipping_fee, uf.idcardnumber, " .
                    "o.pay_status, o.consignee, o.address, o.email, o.tel, o.extension_code, o.extension_id, " .
                    "(" . order_amount_field('o.') . ") AS total_fee, " .
                    " IFNULL(u.user_name, '" .$GLOBALS['_LANG']['anonymous']. "') AS buyer, ".
                    " (SELECT COUNT(*) FROM " . $GLOBALS['ecs']->table('order_info') . " WHERE user_id = o.user_id AND (order_status != 2 OR order_status != 3) ) AS user_order_number ".
                " FROM " . $GLOBALS['ecs']->table('order_info') . " AS o " .
                " LEFT JOIN " .$GLOBALS['ecs']->table('user_freeplan'). " AS uf ON uf.user_id=o.user_id ".
                " LEFT JOIN " .$GLOBALS['ecs']->table('users'). " AS u ON u.user_id=o.user_id ". $where .
                " ORDER BY $filter[sort_by] $filter[sort_order] ".
                " LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";

        foreach (array('order_sn', 'consignee', 'email', 'address', 'zipcode', 'tel', 'user_name') AS $val)
        {
            $filter[$val] = stripslashes($filter[$val]);
        }
        set_filter($filter, $sql);
    }
    else
    {
        $sql    = $result['sql'];
        $filter = $result['filter'];
    }
    $row = $GLOBALS['db']->getAll($sql);
    
    /* 格式话数据 */
    foreach ($row AS $key => $value)
    {
        $row[$key]['isjoin'] = $value['join_id']>0 ? '<span style="color:red">已合单,</span>' : '';
        $row[$key]['formated_order_amount'] = price_format($value['order_amount']);
        $row[$key]['formated_money_paid'] = price_format($value['money_paid']);
        $row[$key]['formated_total_fee'] = price_format($value['total_fee']);
        $row[$key]['formated_shipping_fee'] = price_format($value['shipping_fee']);
        $row[$key]['short_order_time'] = local_date('m-d H:i', $value['add_time']);
        $row[$key]['province'] = selectaddress($value['province']);
        $row[$key]['city'] = selectaddress($value['city']);
        $row[$key]['district'] = selectaddress($value['district']);
        if ($value['order_status'] == OS_INVALID || $value['order_status'] == OS_CANCELED)
        {
            /* 如果该订单为无效或取消则显示删除链接 */
            $row[$key]['can_remove'] = 1;
        }
        else
        {
            $row[$key]['can_remove'] = 0;
        }
    }
    $arr = array('orders' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
    return $arr;
}

function goods_list(){
        $filter['warn']             = empty($_REQUEST['warn']) ? '' : trim($_REQUEST['warn']);//缺货筛选
        $filter['keyword']          = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        // $filter['is_on_sale'] = isset($_REQUEST['is_on_sale']) ? ((empty($_REQUEST['is_on_sale']) && $_REQUEST['is_on_sale'] === 0) ? '' : trim($_REQUEST['is_on_sale'])) : '';
        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        $filter['area_id']          = empty($_REQUEST['area_id']) ? 0 : intval($_REQUEST['area_id']);
        $where = 'WHERE g.is_delete = 0 ';
        /* 关键字 */
        if (!empty($filter['keyword']))
        {
            $where .= " AND (g.goods_id LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR gs.goods_sku LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR g.goods_name LIKE '%" . mysql_like_quote($filter['keyword']) . "%')";
        }
        /*如果启用库存警告*/
        if (!empty($filter['warn']))
        {
            $where .= "AND (gs.goods_number<gs.remind_num)";
        }
        /* 如果管理员属于某个办事处，只列出这个办事处管辖的商品 */
        $sql = "SELECT agency_id FROM " . $GLOBALS['ecs']->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
        $agency_id = $GLOBALS['db']->getOne($sql);
        if ($agency_id > 0)
        {
            $where .= " AND as.area_id = '$agency_id' ";
        }
        elseif($filter['area_id']>0){
            $where .= " AND gs.area_id = '$filter[area_id] ' ";
        }
        /* 分页大小 */
        $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);
        if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
        {
            $filter['page_size'] = intval($_REQUEST['page_size']);
        }
        elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
        {
            $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
        }
        else
        {
            $filter['page_size'] = 15;
        }
        //查询总页数

        $sql = " SELECT g.goods_id,g.goods_name,ga.attr_value,gs.goods_attr_id,gs.area_id,gs.goods_xprice,gs.goods_number,gs.goods_sku,gs.remind_num,sa.area_name ".
                " FROM ". $GLOBALS['ecs']->table('goods_stock') ."AS gs".
                " LEFT JOIN ".$GLOBALS['ecs']->table('goods')." AS g ON g.goods_id=gs.goods_id".
                " LEFT JOIN ".$GLOBALS['ecs']->table('goods_attr')." AS ga ON gs.goods_attr_id=ga.goods_attr_id".
                " LEFT JOIN ".$GLOBALS['ecs']->table('service_area')." AS sa ON sa.area_id=gs.area_id ".$where.
                " AND (((SELECT count(*) FROM " . $GLOBALS['ecs']->table('goods_attr') . " WHERE goods_id = gs.goods_id) = 0 AND gs.goods_attr_id = 0) OR gs.goods_attr_id > 0)";
                // " AND (g.goods_id=ga.goods_id )".
        $filter['record_count'] = $GLOBALS['db']->num_rows($GLOBALS['db']->query($sql)); // 总数
        $filter['page_count']   = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1; // 总页码
        $sql .= " LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]"; // 调取页码数量
        $row = $GLOBALS['db']->getAll($sql);
        /* 格式化数据 */
        foreach ($row AS $key => $value)
        {
            $sql = "SELECT SUM(og.goods_number) AS plan_stock ".
            " FROM ".$GLOBALS['ecs']->table('order_goods')." AS og".
            " LEFT JOIN ".$GLOBALS['ecs']->table('order_info')." AS oi ON og.order_id=oi.order_id".
            " WHERE oi.shipping_status = 0 ".
            " AND oi.order_status !=2 ".
            " AND oi.order_status !=3 ".
            " AND oi.agency_id =$value[area_id] ".
            " AND (og.goods_sku = $value[goods_sku] OR og.goods_attr_sku = $value[goods_sku])";
            $plan_stock[$key] = $GLOBALS['db']->getOne($sql);
            $row[$key]['plan_stock']=$plan_stock[$key];
        }
        $arr = array('goods' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
        return $arr;
}

function buy_list(){


        // $filter['cat_id']           = empty($_REQUEST['cat_id']) ? 0 : intval($_REQUEST['cat_id']);
        // $filter['intro_type']       = empty($_REQUEST['intro_type']) ? '' : trim($_REQUEST['intro_type']);
        // $filter['is_promote']       = empty($_REQUEST['is_promote']) ? 0 : intval($_REQUEST['is_promote']);
        // $filter['stock_warning']    = empty($_REQUEST['stock_warning']) ? 0 : intval($_REQUEST['stock_warning']);
        // $filter['brand_id']         = empty($_REQUEST['brand_id']) ? 0 : intval($_REQUEST['brand_id']);
        $filter['keyword']          = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        // $filter['is_on_sale'] = isset($_REQUEST['is_on_sale']) ? ((empty($_REQUEST['is_on_sale']) && $_REQUEST['is_on_sale'] === 0) ? '' : trim($_REQUEST['is_on_sale'])) : '';
        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        // $filter['sort_by']          = empty($_REQUEST['sort_by']) ? 'goods_id' : trim($_REQUEST['sort_by']);
        // $filter['sort_order']       = empty($_REQUEST['sort_order']) ? 'DESC' : trim($_REQUEST['sort_order']);
        // $filter['is_delete']        = $is_delete;
        $filter['buy_id']          = empty($_REQUEST['buy_id']) ? 0 : intval($_REQUEST['buy_id']);
        $filter['area_id']          = empty($_REQUEST['area_id']) ? 0 : intval($_REQUEST['area_id']);
        $where = 'WHERE 1 ';




        // $filter['keyword']=2015;
        /* 关键字 */
        if (!empty($filter['keyword']))
        {
            $where .= " AND (bi.buy_sn LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR bi.note LIKE '%" . mysql_like_quote($filter['keyword']) . "%' )";
        }
        /*进货ID*/
        if (!empty($filter['buy_id']))
        {
            $where .= " AND bi.buy_id=$filter[buy_id]";
        }


        /* 如果管理员属于某个办事处，只列出这个办事处管辖的商品 */
        $sql = "SELECT agency_id FROM " . $GLOBALS['ecs']->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
        $agency_id = $GLOBALS['db']->getOne($sql);

         // $filter['area_id'] =1;
        if ($agency_id > 0)
        {
            $where .= " AND bi.area_id = '$agency_id' ";
        }
        elseif($filter['area_id']>0){
            $where .= " AND (bi.area_id = '$filter[area_id] ') ";
        }

        /* 分页大小 */
        $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);
        if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
        {
            $filter['page_size'] = intval($_REQUEST['page_size']);
        }
        elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
        {
            $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
        }
        else
        {
            $filter['page_size'] = 15;
        }
        //查询总页数
        $sql=" SELECT  COUNT(*)".
             " FROM ". $GLOBALS['ecs']->table('ware_buy_info') ." AS bi ".
             $where;
        $filter['record_count']   = $GLOBALS['db']->getOne($sql);
        $filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;
        $sql=" SELECT bi.*,a.agency_name AS area_name,SUM(bg.goods_number) AS goods_number,SUM(bg.goods_price*bg.goods_number) AS amount".
             " FROM ". $GLOBALS['ecs']->table('ware_buy_info') ." AS bi".
             " LEFT JOIN ".$GLOBALS['ecs']->table('ware_buy_goods')." AS bg ON bg.buy_id=bi.buy_id ".
             " LEFT JOIN ".$GLOBALS['ecs']->table('agency')." AS a ON a.agency_id=bi.area_id ".
             $where.
             " group by bi.buy_id".
             " ORDER BY  bi.buy_id DESC ".
             " LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";

        $row = $GLOBALS['db']->getAll($sql);
            /* 格式化数据 */
        foreach ($row AS $key => $value)
        {
            $row[$key]["add_time"]=date('Y-m-d H:i:s',$value['add_time']);
            switch ($value['buy_code']) {
                case '1':
                    $row[$key]["from_name"]="供货商";
                    break;
                case '2':
                    $row[$key]["from_name"]="调配";
                    break;
                case '3':
                    $row[$key]["from_name"]="退货品";
                    break;
                
                default:
                    # code...
                    break;
            }
        }
     
        $arr = array('buy' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
        return $arr;
}
/*进货统计*/
function buy_stats_list(){
        $filter['keyword']          = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);//关键字
        $filter['area_id']          = empty($_REQUEST['area_id']) ? 0 : intval($_REQUEST['area_id']);
        $filter['start_date']  = !empty($_POST['start_date'])?strtotime($_POST['start_date'].' 00:00:00'):(time()-86400);//开始时间
        $filter['end_date'] = !empty($_POST['end_date'])?strtotime($_POST['end_date'].' 23:59:59'):(time());//结束时间

        $where = 'WHERE 1 ';
        // $filter['keyword']=2015;
        /* 关键字 */
        if (!empty($filter['keyword']))
        {
            $where .= " AND ( bg.goods_name  LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR bg.goods_sku  LIKE '%" . mysql_like_quote($filter['keyword']) . "%' )";
        }
        /*时间段*/
        if(!empty($filter['start_date'])){
            $where .= " AND ( bi.add_time > $filter[start_date] AND bi.add_time < $filter[end_date])";
        }

        /* 如果管理员属于某个办事处，只列出这个办事处管辖的进货统计 */
        $sql = "SELECT agency_id FROM " . $GLOBALS['ecs']->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
        $agency_id = $GLOBALS['db']->getOne($sql);

         // $filter['area_id'] =1;
        if ($agency_id > 0)
        {
            $where .= " AND bi.area_id = '$agency_id' ";
        }
        elseif($filter['area_id']>0){
            $where .= " AND (bi.area_id = '$filter[area_id] ') ";
        }

        /* 分页大小 */
        $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);
        if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
        {
            $filter['page_size'] = intval($_REQUEST['page_size']);
        }
        elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
        {
            $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
        }
        else
        {
            $filter['page_size'] = 15;
        }

        $sql=" SELECT bg.goods_id,bg.goods_sku,bg.goods_name,bg.goods_attr_name,sum(bg.goods_number) AS total_number ,sum(bg.goods_price) AS total_price". 
             " FROM ".$GLOBALS['ecs']->table('ware_buy_goods') ." AS bg".
             " LEFT JOIN ".$GLOBALS['ecs']->table('ware_buy_info')." AS bi ON bg.buy_id=bi.buy_id ".
             $where.
             " group by bg.goods_sku";
        $filter['record_count'] = $GLOBALS['db']->num_rows($GLOBALS['db']->query($sql)); // 总数
        $filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;//总数
        $sql = $sql." LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";
        $row = $GLOBALS['db']->getAll($sql);
        $arr = array('buy' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
        return $arr;
}
/*出货单列表*/
function out_list(){
        $filter['keyword']          = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);
        if (isset($_REQUEST['is_ajax']) && $_REQUEST['is_ajax'] == 1)
        {
            $filter['keyword'] = json_str_iconv($filter['keyword']);
        }
        $filter['out_id']          = empty($_REQUEST['out_id']) ? 0 : intval($_REQUEST['out_id']);
        $filter['area_id']          = empty($_REQUEST['area_id']) ? 0 : intval($_REQUEST['area_id']);
        $where = 'WHERE 1 ';
        /* 关键字 */
        if (!empty($filter['keyword']))
        {
            $where .= " AND (oi.out_sn LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR oi.note LIKE '%" . mysql_like_quote($filter['keyword']) . "%' )";
        }
        /*出货ID*/
        if (!empty($filter['out_id']))
        {
            $where .= " AND oi.out_id=$filter[out_id]";
        }


        /* 如果管理员属于某个办事处，只列出这个办事处管辖的商品 */
        $sql = "SELECT agency_id FROM " . $GLOBALS['ecs']->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
        $agency_id = $GLOBALS['db']->getOne($sql);
        if ($agency_id > 0)
        {
            $where .= " AND oi.area_id = '$agency_id' ";
        }
        elseif($filter['area_id']>0){
            $where .= " AND (oi.area_id = '$filter[area_id] ') ";
        }

        /* 分页大小 */
        $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);
        if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
        {
            $filter['page_size'] = intval($_REQUEST['page_size']);
        }
        elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
        {
            $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
        }
        else
        {
            $filter['page_size'] = 15;
        }
        //查询总页数
        $sql=" SELECT  COUNT(*)".
             " FROM ". $GLOBALS['ecs']->table('ware_out_info') ." AS oi ".
             $where;
        $filter['record_count']   = $GLOBALS['db']->getOne($sql);
        $filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;
        $sql=" SELECT oi.*,a.agency_name AS area_name,SUM(og.goods_number) AS goods_number,SUM(og.goods_price*og.goods_number) AS amount".
             " FROM ". $GLOBALS['ecs']->table('ware_out_info') ." AS oi".
             " LEFT JOIN ".$GLOBALS['ecs']->table('ware_out_goods')." AS og ON og.out_id=oi.out_id ".
             " LEFT JOIN ".$GLOBALS['ecs']->table('agency')." AS a ON a.agency_id=oi.area_id ".
             $where.
             " group by oi.out_id".
             " ORDER BY oi.out_id  DESC ".
             " LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";
        $row = $GLOBALS['db']->getAll($sql);
            /* 格式化数据 */
        foreach ($row AS $key => $value)
        {
            $row[$key]["add_time"]=date('Y-m-d H:i:s',$value['add_time']);
            switch ($value['out_code']) {
                case '1':
                    $row[$key]["from_name"]="报损";
                    break;
                case '2':
                    $row[$key]["from_name"]="调配";
                    break;
                case '3':
                    $row[$key]["from_name"]="线下订单";
                    break;
                case '4':
                    $row[$key]["from_name"]="补发";
                    break;
                default:
                    # code...
                    break;
            }
        }
        $arr = array('out' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
        return $arr;
}

/*出货统计*/
function out_stats_list(){
        $filter['keyword']          = empty($_REQUEST['keyword']) ? '' : trim($_REQUEST['keyword']);//关键字
        $filter['area_id']          = empty($_REQUEST['area_id']) ? 0 : intval($_REQUEST['area_id']);
        $filter['start_date']  = !empty($_POST['start_date'])?strtotime($_POST['start_date'].' 00:00:00'):(time()-86400);//开始时间
        $filter['end_date'] = !empty($_POST['end_date'])?strtotime($_POST['end_date'].' 23:59:59'):(time());//结束时间

        $where = 'WHERE 1 ';
        // $filter['keyword']=2015;
        /* 关键字 */
        if (!empty($filter['keyword']))
        {
            $where .= " AND ( og.goods_name  LIKE '%" . mysql_like_quote($filter['keyword']) . "%' OR og.goods_sku  LIKE '%" . mysql_like_quote($filter['keyword']) . "%' )";
        }
        /*时间段*/
        if(!empty($filter['start_date'])){
            $where .= " AND ( oi.add_time > $filter[start_date] AND oi.add_time < $filter[end_date])";
        }

        /* 如果管理员属于某个办事处，只列出这个办事处管辖的进货统计 */
        $sql = "SELECT agency_id FROM " . $GLOBALS['ecs']->table('admin_user') . " WHERE user_id = '$_SESSION[admin_id]'";
        $agency_id = $GLOBALS['db']->getOne($sql);

         // $filter['area_id'] =1;
        if ($agency_id > 0)
        {
            $where .= " AND oi.area_id = '$agency_id' ";
        }
        elseif($filter['area_id']>0){
            $where .= " AND (oi.area_id = '$filter[area_id] ') ";
        }

        /* 分页大小 */
        $filter['page'] = empty($_REQUEST['page']) || (intval($_REQUEST['page']) <= 0) ? 1 : intval($_REQUEST['page']);
        if (isset($_REQUEST['page_size']) && intval($_REQUEST['page_size']) > 0)
        {
            $filter['page_size'] = intval($_REQUEST['page_size']);
        }
        elseif (isset($_COOKIE['ECSCP']['page_size']) && intval($_COOKIE['ECSCP']['page_size']) > 0)
        {
            $filter['page_size'] = intval($_COOKIE['ECSCP']['page_size']);
        }
        else
        {
            $filter['page_size'] = 15;
        }

        $sql=" SELECT og.goods_id,og.goods_sku,og.goods_name,og.goods_attr_name,sum(og.goods_number) AS total_number ,sum(og.goods_price) AS total_price". 
             " FROM ".$GLOBALS['ecs']->table('ware_out_goods') ." AS og".
             " LEFT JOIN ".$GLOBALS['ecs']->table('ware_out_info')." AS oi ON og.out_id=oi.out_id ".
             $where.
             " group by og.goods_sku";

        $filter['record_count'] = $GLOBALS['db']->num_rows($GLOBALS['db']->query($sql)); // 总数
        $filter['page_count']     = $filter['record_count'] > 0 ? ceil($filter['record_count'] / $filter['page_size']) : 1;//总数
        $sql = $sql." LIMIT " . ($filter['page'] - 1) * $filter['page_size'] . ",$filter[page_size]";
        $row = $GLOBALS['db']->getAll($sql);
        
        $arr = array('buy' => $row, 'filter' => $filter, 'page_count' => $filter['page_count'], 'record_count' => $filter['record_count']);
        return $arr;
}

/**
 *  记录仓库操作
 *
 * @access  public
 * @param   $user_name  操作员名字
 * @param   $log_type  操作类型
 * @param   $code  操作备注 
 * @return void
 */
function ware_log($user_name,$log_type,$code,$area_id){
    $tmie=time();
    switch ($log_type) {
        case '1':
        $log_info="商品发货";
            break;
        case '2':
        $log_info="取消发货";
            break;
        case '3':
        $log_info="修改发货单号";   
            break;
        case '4':
        $log_info="进货";  
            break;  
        case '5':
        $log_info="出货"; 
            break;         
        default:
            # code...
            break;
    }
    $sql = 'INSERT INTO ' . $GLOBALS['ecs']->table('ware_log') . ' (log_time, user_name, log_type,log_info,code,area_id) ' .
            "VALUES('$tmie', '$user_name', '$log_type' , '$log_info' ,'$code','$area_id')";
    $GLOBALS['db']->query($sql);
}
/**
 *  出货单信息
 *
 * @access  public
 * @param   $out_id  出货单ID
 * @return  $out_info
 */
function out_info($out_id){
        //获取出货单商品
        $sql="SELECT * FROM ".$GLOBALS['ecs']->table('ware_out_goods')." WHERE out_id = $out_id";
        $goods_list=$GLOBALS['db']->getAll($sql);
        foreach ($goods_list as $key => $value) {
            $goods_list[$key]['subtotal']=number_format($value['goods_price']*$value['goods_number'],2);
        }
        $out_list = out_list();//出货单列表
        $out_info['info']= $out_list['out']['0'];
        $out_info['goods']=$goods_list;
        return $out_info ;
}
/**
 *  进货单信息
 *
 * @access  public
 * @param   $out_id  出货单ID
 * @return  $buy_info
 */
function buy_info($buy_id){
        //获取出货单商品
        $sql="SELECT * FROM ".$GLOBALS['ecs']->table('ware_buy_goods')." WHERE buy_id = $buy_id";
        $goods_list=$GLOBALS['db']->getAll($sql);
        foreach ($goods_list as $key => $value) {
            $goods_list[$key]['subtotal']=number_format($value['goods_price']*$value['goods_number'],2);
        }
        $buy_list = buy_list();//出货单列表
        $buy_info['info']= $buy_list['buy']['0'];
        $buy_info['goods']=$goods_list;
        return $buy_info ;
}


 ?>